package chd.edu.spzx.common.log.aspect;

import chd.edu.spzx.common.log.annotation.Log;
import chd.edu.spzx.common.log.service.AsyncOperLogService;
import chd.edu.spzx.common.log.utils.LogUtil;
import chd.edu.spzx.model.entity.system.SysOperLog;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * 环绕通知切面类定义
 * @author Zhang Chaoliang
 * create 2023
 */
@Aspect
@Component
public class LogAspect {

    @Autowired
    private AsyncOperLogService asyncOperLogService ;

    /**
     * 环绕通知
     * @param joinPoint
     * @param sysLog
     * @return
     */
    @Around(value = "@annotation(sysLog)")
    public Object doAroundAdvice(ProceedingJoinPoint joinPoint, Log sysLog){

//        String title = sysLog.title();
//        int businessType = sysLog.businessType();
//        System.out.println("title: "+title +" :: businessType: "+businessType);

        //业务方法调用之前，先封装数据
        SysOperLog sysOperLog = new SysOperLog() ;

        LogUtil.beforeHandleLog(sysLog , joinPoint , sysOperLog) ;

        //业务方法调用
        Object proceed = null;
        try {
            proceed = joinPoint.proceed();

//            System.out.println("在业务方法之后执行...");
            //业务方法调用之后，封装数据
            LogUtil.afterHandlLog(sysLog , proceed , sysOperLog , 0 , null) ;

        } catch (Throwable e) {
            e.printStackTrace();                                // 打印异常信息
            LogUtil.afterHandlLog(sysLog , proceed , sysOperLog , 1 , e.getMessage()) ;
            throw new RuntimeException();
        }

        //调用service方法把日志信息添加到数据库中
        asyncOperLogService.saveSysOperLog(sysOperLog);

        return  proceed;
    }
}
